﻿/*******************************************************************************
 * CreateTime:2022-04-04 11:38:15
 * Description: YoursLC有源低代码
*********************************************************************************/

using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;
using Think9.Services.Table;
using Think9.Services.Flow;
using Think9.Util.Helper;

namespace Think9.Services.CodeBuild
{
	/// <summary>
	/// 子表Service
	/// </summary>
	public class DeliveryDetailsService : BaseService<DeliveryDetailsModel>
	{
		private ComService ComService = new ComService();
		private string split = BaseUtil.ComSplit;//字符分割 用于多选项的分割等 如split+选项1+split+选项2+split
		private string sql;
		private string str;
		private string v3 = "";//保存option 通过GetSelectList赋值
		private string v4 = "";//保存option 通过GetSelectList赋值


		/// <summary>
		/// 返回子表数据
		/// </summary>
		/// <param name="listid"></param>
		/// <returns></returns>
		public List<DeliveryDetailsModel> GetGridDataByListId(CurrentUserEntity user, int listid, string from)
		{
			int count = 0;//行号
			DataTable dtindex = ComService.GetDataTable("select IndexId, BLock,BLock2,DataType,ControlType,DefaultV,RuleId,ListStat from tbindex where TbId = 'tb_DeliveryDetails'  order by IndexNo");

			this.GetSelectList();

			List<DeliveryDetailsModel> list = new List<DeliveryDetailsModel>();
			//首行 待添加行 录入表基本属性可设置为可动态添加删除行
			DeliveryDetailsModel objAdd = new DeliveryDetailsModel();
			objAdd.ListId = listid;
			objAdd.Id = 0;//首行Id = 0
			objAdd.TbId = "tb_DeliveryDetails";
			objAdd.flag = "#tb_DeliveryDetails#0#0#";
			objAdd.v1_JS ="  onclick = \" PopUpSelectValue('tb_DeliveryDetails','v1','"+ objAdd.Id.ToString() +"') \"  ";
			objAdd.v1_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v1");
			objAdd.v1_Lock = BasicHelp.GetGridLockStr(dtindex, "v1", 0, from);
			objAdd.v2_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v2");
			objAdd.v2_Lock = BasicHelp.GetGridLockStr(dtindex, "v2", 0, from);
			objAdd.v3_Exa = this.v3;
			objAdd.v3_Lock = BasicHelp.GetGridLockStr(dtindex, "v3", 0, from);
			objAdd.v4_Exa = this.v4;
			objAdd.v4_Lock = BasicHelp.GetGridLockStr(dtindex, "v4", 0, from);
			objAdd.v5_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v5");
			objAdd.v5_Lock = BasicHelp.GetGridLockStr(dtindex, "v5", 0, from);
			objAdd.v6_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v6");
			objAdd.v6_Lock = BasicHelp.GetGridLockStr(dtindex, "v6", 0, from);
			objAdd.v7_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v7");
			objAdd.v7_Lock = BasicHelp.GetGridLockStr(dtindex, "v7", 0, from);
			objAdd.v8_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v8");
			objAdd.v8_Lock = BasicHelp.GetGridLockStr(dtindex, "v8", 0, from);
			objAdd.v9_Exa = BasicHelp.GetDefaultValue(user, dtindex, "v9");
			objAdd.v9_Lock = BasicHelp.GetGridLockStr(dtindex, "v9", 0, from);
			list.Add(objAdd);


			IEnumerable<DeliveryDetailsModel> _list = base.GetByWhere("where ListId=" + listid + "", null, null, "ORDER BY id");
			foreach (DeliveryDetailsModel obj in _list)
			{
				count++;//第几行 用于按行锁定等

				obj.TbId = "tb_DeliveryDetails";
				obj.flag = "#tb_DeliveryDetails#" + obj.Id.ToString() + "#" + count.ToString() + "#";
				//文本框商品编号
				obj.v1_JS ="  onclick = \" PopUpSelectValue('tb_DeliveryDetails','v1','"+ obj.Id.ToString() +"') \"  ";
				obj.v1_Exa = obj.v1 == null ? "" : obj.v1.ToString();
				obj.v1_Lock = BasicHelp.GetGridLockStr(dtindex, "v1", count, from);
				//文本框商品名称
				obj.v2_Exa = obj.v2 == null ? "" : obj.v2.ToString();
				obj.v2_Lock = BasicHelp.GetGridLockStr(dtindex, "v2", count, from);
				//select下拉选择单位
				str = obj.v3 == null ? "" : obj.v3.ToString();
				obj.v3_Exa = this.v3.Replace("<option value='"+ str +"'>", "<option value='"+ str +"' selected>");
				obj.v3_Lock = BasicHelp.GetGridLockStr(dtindex, "v3", count, from);
				//select下拉选择颜色
				str = obj.v4 == null ? "" : obj.v4.ToString();
				obj.v4_Exa = this.v4.Replace("<option value='"+ str +"'>", "<option value='"+ str +"' selected>");
				obj.v4_Lock = BasicHelp.GetGridLockStr(dtindex, "v4", count, from);
				//文本框规格型号
				obj.v5_Exa = obj.v5 == null ? "" : obj.v5.ToString();
				obj.v5_Lock = BasicHelp.GetGridLockStr(dtindex, "v5", count, from);
				//文本框单价
				obj.v6_Exa = obj.v6 == null ? "" : obj.v6.ToString();
				obj.v6_Lock = BasicHelp.GetGridLockStr(dtindex, "v6", count, from);
				//文本框数量
				obj.v7_Exa = obj.v7 == null ? "" : obj.v7.ToString();
				obj.v7_Lock = BasicHelp.GetGridLockStr(dtindex, "v7", count, from);
				//文本框金额
				obj.v8_Exa = obj.v8 == null ? "" : obj.v8.ToString();
				obj.v8_Lock = BasicHelp.GetGridLockStr(dtindex, "v8", count, from);
				//文本框备注
				obj.v9_Exa = obj.v9 == null ? "" : obj.v9.ToString();
				obj.v9_Lock = BasicHelp.GetGridLockStr(dtindex, "v9", count, from);
				list.Add(obj);
			}

			//合计行
			DeliveryDetailsModel sumobj = GetSumObj(listid, "tb_DeliveryDetails", dtindex);
			if (sumobj.ListId != -1)
			{
				list.Add(sumobj);
			}

			return list;
		}
	   
	   /// <summary>
	   /// 将前台返回的json对象转化为通用子表对象 并进行格式及能否为空校验
	   /// </summary>
	   /// <param name="list"></param>
	   /// <param name="flag"></param>
	   /// <param name="listid"></param>
	   /// <param name="strErr"></param>
	   /// <returns></returns>
	   public static List<DeliveryDetailsModel> GetGridFormList(IEnumerable<GridListEntity> list, string flag, int listid, ref string strErr)
		{
			string id = "";
			string row = "";
			string err = "";
			string tbid = "tb_DeliveryDetails";
			string temp = "";
			bool badd = false;

			List<DeliveryDetailsModel> mlist = new List<DeliveryDetailsModel>();

			foreach (GridListEntity obj in list)
			{
				badd = false;
				if (!string.IsNullOrEmpty(flag))//添加一条数据
				{
					if (obj.flag.StartsWith(flag))
					{
						badd = true;
					}
				}
				else//编辑列表数据
				{
                    //排除首行即增加行
                    if (obj.flag.StartsWith("#" + tbid + "#") && !obj.flag.EndsWith("#0#0#"))
                    {
                        badd = true;
                    }
				}

				if (badd)
				{
					err = "";
					BasicHelp.GetRowAndIdByFlag(obj.flag, ref id, ref row);

					//商品编号
					if (string.IsNullOrEmpty(obj.v1))
					{
						err += row + "商品编号不能为空";
					}
					//商品名称
					if (string.IsNullOrEmpty(obj.v2))
					{
						err += row + "商品名称不能为空";
					}
					temp = obj.v6 == null ? "" : obj.v6;
					if (!ValidatorHelper.IsNumberic(temp) && !string.IsNullOrEmpty(temp))
					{
						err += row + "单价数字格式错误";
					}
					//数量
					if (string.IsNullOrEmpty(obj.v7))
					{
						err += row + "数量不能为空";
					}
					temp = obj.v7 == null ? "" : obj.v7;
					if (!ValidatorHelper.IsNumberic(temp) && !string.IsNullOrEmpty(temp))
					{
						err += row + "数量数字格式错误";
					}
					temp = obj.v8 == null ? "" : obj.v8;
					if (!ValidatorHelper.IsNumberic(temp) && !string.IsNullOrEmpty(temp))
					{
						err += row + "金额数字格式错误";
					}

					if (string.IsNullOrEmpty(err))
					{
						DeliveryDetailsModel model = new DeliveryDetailsModel();
						model.TbId = tbid;
						model.ListId = listid;
						model.Id = int.Parse(id);
						model.v1 = obj.v1 == null ? "" : obj.v1;
						model.v2 = obj.v2 == null ? "" : obj.v2;
						model.v3 = obj.v3 == null ? "" : obj.v3;
						model.v4 = obj.v4 == null ? "" : obj.v4;
						model.v5 = obj.v5 == null ? "" : obj.v5;
						model.v6 = string.IsNullOrEmpty(obj.v6) ? null : decimal.Parse(obj.v6);
						model.v7 = string.IsNullOrEmpty(obj.v7) ? null : decimal.Parse(obj.v7);
						model.v8 = string.IsNullOrEmpty(obj.v8) ? null : decimal.Parse(obj.v8);
						model.v9 = obj.v9 == null ? "" : obj.v9;

						mlist.Add(model);
					}
					else
					{
						strErr += "出库明细 " + err;
					}
				}
			}

			return mlist;
		}



		//子表 为下拉选择、多选、单选动态数据源 来源于为指标指定的数据规范
		public IEnumerable<valueTextEntity> GetSelectList()
		{
			DataTable dt = DataTableHelp.NewValueTextDt();

			//单位
			sql = "select DetailName as id,DetailName as name FROM sys_itemsdetail where ItemCode = 'UnitOfMeasure' ORDER BY OrderNo";
			foreach (DataRow dr in ComService.GetDataTable(sql).Rows)
			{
				this.v3 += "<option value='"+ dr["id"].ToString() +"'>" + dr["name"].ToString() + "</option>";
				//DataRow row = dt.NewRow();
				//row["ClassID"] = "tb_DeliveryDetailsv3";
				//row["Value"] = dr["id"].ToString();
				//row["Text"] = dr["name"].ToString();
				//dt.Rows.Add(row);
			}
			//颜色
			sql = "select DetailCode as id,DetailName as name FROM sys_itemsdetail where ItemCode = 'Colour' ORDER BY OrderNo";
			foreach (DataRow dr in ComService.GetDataTable(sql).Rows)
			{
				this.v4 += "<option value='"+ dr["id"].ToString() +"'>" + dr["name"].ToString() + "</option>";
				//DataRow row = dt.NewRow();
				//row["ClassID"] = "tb_DeliveryDetailsv4";
				//row["Value"] = dr["id"].ToString();
				//row["Text"] = dr["name"].ToString();
				//dt.Rows.Add(row);
			}

			//DataTable转换成IEnumerable
			return DataTableHelp.ToEnumerable<valueTextEntity>(dt);
		}

		//合计行
		private DeliveryDetailsModel GetSumObj(int listid, string tbid, DataTable dtindex)
		{
			TbIndexService TbIndexService = new TbIndexService();

			DeliveryDetailsModel obj = new DeliveryDetailsModel();
			obj.ListId = -1;

			var _index = DataTableHelp.ToEnumerable<TbIndexEntity>(dtindex);
			if (_index.Where(x => x.ControlType == "1" && x.ListStat == "1" && x.DataType.StartsWith("3")).Count<TbIndexEntity>() > 0)//条件 1数值指标2文本框3统计求和
			{
				obj.ListId = listid;
				obj.Id = -1;
				obj.TbId = tbid;
				obj.flag = "";
				foreach (TbIndexEntity item in _index)
				{
				    //1数值指标2文本框3统计求和
					if (item.ControlType == "1" && item.ListStat == "1" && item.DataType.StartsWith("3"))
					{
						switch (item.IndexId)
						{
							case "v1":
								obj.v1_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v1_Lock = "disabled = 'disabled'";
								break;
							case "v2":
								obj.v2_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v2_Lock = "disabled = 'disabled'";
								break;
							case "v3":
								obj.v3_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v3_Lock = "disabled = 'disabled'";
								break;
							case "v4":
								obj.v4_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v4_Lock = "disabled = 'disabled'";
								break;
							case "v5":
								obj.v5_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v5_Lock = "disabled = 'disabled'";
								break;
							case "v6":
								obj.v6_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v6_Lock = "disabled = 'disabled'";
								break;
							case "v7":
								obj.v7_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v7_Lock = "disabled = 'disabled'";
								break;
							case "v8":
								obj.v8_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v8_Lock = "disabled = 'disabled'";
								break;
							case "v9":
								obj.v9_Exa = "∑ = " + ComService.GetSingle("select SUM(" + item.IndexId + ") from " + obj.TbId + " where ListId = " + listid + "");
								 obj.v9_Lock = "disabled = 'disabled'";
								break;

							default:
								break;
						}
					}
					else
					{
						switch (item.IndexId)
						{
							case "v1":
								obj.v1_Exa = "";
								 obj.v1_Lock = "disabled = 'disabled'";
								break;
							case "v2":
								obj.v2_Exa = "";
								 obj.v2_Lock = "disabled = 'disabled'";
								break;
							case "v3":
								obj.v3_Exa = "";
								 obj.v3_Lock = "disabled = 'disabled'";
								break;
							case "v4":
								obj.v4_Exa = "";
								 obj.v4_Lock = "disabled = 'disabled'";
								break;
							case "v5":
								obj.v5_Exa = "";
								 obj.v5_Lock = "disabled = 'disabled'";
								break;
							case "v6":
								obj.v6_Exa = "";
								 obj.v6_Lock = "disabled = 'disabled'";
								break;
							case "v7":
								obj.v7_Exa = "";
								 obj.v7_Lock = "disabled = 'disabled'";
								break;
							case "v8":
								obj.v8_Exa = "";
								 obj.v8_Lock = "disabled = 'disabled'";
								break;
							case "v9":
								obj.v9_Exa = "";
								 obj.v9_Lock = "disabled = 'disabled'";
								break;

							default:
								break;
						}
					}
				}
			}

			return obj;
		}
		
		//子表数据读取
		public void ReadValue(ref List<ControlEntity> list, CurrentUserEntity user, IEnumerable<ControlEntity> controlslist, IEnumerable<GridListEntity> gridlist, string tbid, string indexid, string value)
		{
			string tbname = "";
			string some = "";
			string where = "";
			string order = "";
			
			if (indexid == "DeliveryDetailsv1")
			{
				//读取商品信息
				tbname = "tb_commodityinformation";
				some = "inTradeName AS v2,inCompany AS v3,inColour AS v4,inSpecificationAndModel AS v5,inPresetPurchasePrice AS v6";
				where = "where tb_commodityinformation.initemnumber = @v1";
				order = " order by listid";
				object param = new { v1 = value };
				
				DataTable dt = ComService.GetDataTable(tbname, some, where, order, param);
				if (dt.Rows.Count > 0)
				{
					//商品名称
					list.Add(new ControlEntity { ControlID = "v2", ControlValue = dt.Rows[0]["v2"].ToString(), ControlType = "1" });
					
					//单位
					list.Add(new ControlEntity { ControlID = "v3", ControlValue = dt.Rows[0]["v3"].ToString(), ControlType = "2" });
					
					//颜色
					list.Add(new ControlEntity { ControlID = "v4", ControlValue = dt.Rows[0]["v4"].ToString(), ControlType = "2" });
					
					//规格型号
					list.Add(new ControlEntity { ControlID = "v5", ControlValue = dt.Rows[0]["v5"].ToString(), ControlType = "1" });
					
					//单价
					list.Add(new ControlEntity { ControlID = "v6", ControlValue = dt.Rows[0]["v6"].ToString(), ControlType = "1" });
					
				}
			}
			
		}
		//子表计算式 根据录入表指标计算式生成
		public void GetCalculationValue(DeliveryDetailsModel obj, SalesDeliveryModel model)
		{
			obj.v8 = obj.v6 * obj.v7;
		}
	}
}